<?php

namespace App\Http\Controllers\Admin;

use App\Http\Model\UserTable;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Validator;

require_once 'resources/org/Code.class.php';
class LoginController extends CommonController
{
    public function login(Request $request){
        if($input = $request->input()){
            $code = new \Code;
            $getcode = $code->get();
            if(strtoupper($input['code'])!=$getcode){
                return back()->with('msg',"验证码错误");
            }
            $user = UserTable::first();
            if($input['user_name']!=$user->user_name||$input['user_pass']!=Crypt::decrypt($user->user_pass)){
                return back()->with('msg',"用户名或者密码错误！");
            }
            session(['user'=>$user]);
            return redirect('admin');
        }else{
            return view('admin.login');
        }
    }

    public function code()
    {
        $code = new \Code;
        $code->make();
    }

    public function getcode()
    {
        $code = new \Code;
        echo $code->get();
    }

//    public function crypt()
//    {
//        $str = "123456";
//        echo Crypt::encrypt($str);
//    }
    public function quit()
    {
        session(['user'=>null]);
        return redirect('admin/login');
    }

    public function pass(Request $request)
    {
        if($input = $request->input()){
            $rules = [
                'password'=>'required|between:6,20|confirmed',
            ];
            $message = [
                'required'=>'请输入密码',
                'between'=>'密码必须为6-20位之间！',
                'confirmed'=>'确认密码不一致!'
            ];
            $validator = Validator::make($input,$rules,$message);
            if($validator->passes()){
                $user = UserTable::first();
                if(Crypt::decrypt($user->user_pass)==$input['password_o']){
                    $user->user_pass = Crypt::encrypt($input['password']);
                    $user->save();
                    return back()->with('errors','密码修改成功！');
                }else{
                    return back()->with('errors',"原密码错误！");
                }
            }else{
                return back()->withErrors($validator);
            }
        } else{
            return view("admin.pass");
        }
    }

    public function haha()
    {
        echo Crypt::encrypt("123456");
    }
}
